import { createApp } from 'vue'
import { addClass, removeClass } from '@/assets/js/dom'

const relativeCls = 'g-relative'
export default function createLoadingLikeDirective (Comp) {
  return {
    mounted (el, binding) {
      // el：指令绑定到的元素。这可以用于直接操作 DOM
      // binding：一个对象，包含以下属性。
      // binding.value：传递给指令的值。例如在 v-my-directive="1 + 1" 中，值是 2。
      const app = createApp(Comp)
      const instance = app.mount(document.createElement('div'))
      const name = Comp.name
      if (!el[name]) {
        el[name] = {}
      }
      // 追加属性，方便访问instance
      el[name].instance = instance
      const title = binding.arg
      if (typeof title !== 'undefined') {
        el[name].instance.setTitle(title)
      }
      if (binding.value) {
        append(el)
      }
    },
    updated (el, binding) {
      if (binding.value !== binding.oldValue) {
        binding.value ? append(el) : remove(el)
      }
    }
  }
  function append (el) {
    const name = Comp.name
    // loading组件添加定位，可以居中对齐
    const style = getComputedStyle(el)
    if (!['absolute', 'fixed', 'relative'].includes(style.position)) {
      addClass(el, relativeCls)
    }
    // el.instance.$el Loading组件dom
    el.appendChild(el[name].instance.$el)
  }
  function remove (el) {
    const name = Comp.name
    removeClass(el, relativeCls)
    el.removeChild(el[name].instance.$el)
  }
}
